package cn.xinzhi.servlet;

import cn.xinzhi.dao.impl.UserInfoDaoImpl;
import cn.xinzhi.entity.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html,charaset=utf-8");
        PrintWriter out = response.getWriter();

        String user = request.getParameter("username");
        String pwd = request.getParameter("password");
        UserInfoDaoImpl uidi = new UserInfoDaoImpl();
        UserInfo ui = uidi.login(user,pwd);
        if (ui != null){
            if ("1".equals(request.getParameter("x"))) {
                Cookie cookie1 = new Cookie("user", "");
                Cookie cookie2 = new Cookie("pwd", "");

                cookie1.setValue(user);//要set一下,这才是设置值，上面不是
                cookie2.setValue(pwd);

                cookie1.setMaxAge(10);//60秒失效
                cookie2.setMaxAge(10);
                response.addCookie(cookie1);//存进去
                response.addCookie(cookie2);
            }
            response.sendRedirect("show.jsp");
        }else {
            response.sendRedirect("login.jsp?flag=0");
        }
        out.flush();
        out.close();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
